package cn.ly.domain.award.service.distribute.impl;

import cn.ly.domain.award.model.aggregate.GiveOutPrizesAggregate;
import cn.ly.domain.award.model.entity.DistributeAwardEntity;
import cn.ly.domain.award.model.entity.UserAwardRecordEntity;
import cn.ly.domain.award.model.entity.UserCreditAwardEntity;
import cn.ly.domain.award.model.valobj.AwardStateVO;
import cn.ly.domain.award.adapter.repository.IAwardRepository;
import cn.ly.domain.award.service.distribute.IDistributeAward;
import cn.ly.types.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * 用户积分奖品，支持 award_config 透传，满足黑名单积分奖励。
 */
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {
    /**
     * 奖品仓储注入
     */
    @Resource
    private IAwardRepository awardRepository;

    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) throws Exception{
        // 奖品ID
        Integer awardId = distributeAwardEntity.getAwardId();
        // 查询奖品ID 「优先走透传的随机积分奖品配置」
        String awardConfig = distributeAwardEntity.getAwardConfig();
        if (StringUtils.isBlank(awardConfig)) {
            awardConfig = awardRepository.queryAwardConfig(awardId);
        }

        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if (creditRange.length != 2) {
            throw new RuntimeException("award_config 「" + awardConfig + "」配置不是一个范围值，如 1,100");
        }
        // 根据奖品配置项生成随机积分
        BigDecimal randomCredit = generateRandom(new BigDecimal(creditRange[0]),new BigDecimal(creditRange[1]));
        // 构建聚合对象
        // 1. 用户中奖记录实体
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buildDistributeUserAwardRecordEntity(
                distributeAwardEntity.getUserId(), distributeAwardEntity.getOrderId(), distributeAwardEntity.getAwardId(), AwardStateVO.create);
        // 2. 用户积分奖品实体
        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(distributeAwardEntity.getUserId(), randomCredit);

        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(distributeAwardEntity.getUserId());
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecordEntity);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAwardEntity);

        awardRepository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);

    }


    private BigDecimal generateRandom(BigDecimal min, BigDecimal max) {
        if (min.equals(max)) return min;
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3));
    }
}
